package com.heima.a07_demo.server.service.impl;

import com.heima.a07_demo.pojo.vo.DashboardVO;
import com.heima.a07_demo.server.mapper.DiagnosisRecordMapper;
import com.heima.a07_demo.server.service.DiagnosisRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DiagnosisRecordServiceImp implements DiagnosisRecordService {

    @Autowired
    private DiagnosisRecordMapper diagnosisRecordMapper;

    @Override
    public DashboardVO getDiagnosisRecordById(Long id) {
        // 查询今日诊断数
        Integer todayRecord = diagnosisRecordMapper.countTodayRecord(id);
        Integer yesterdayRecord = diagnosisRecordMapper.countYesterdayRecord(id);

        // 计算增长率（防止除零异常）
        double dayGrowthRate = (yesterdayRecord == null || yesterdayRecord == 0)
                ? 1.0
                : (todayRecord - yesterdayRecord) * 1.0 / yesterdayRecord;

        // 查询累计诊断量
        Integer allRecord = diagnosisRecordMapper.countAllRecord(id);
        Integer lastMonthRecord = diagnosisRecordMapper.countLastMonthRecord(id);

        double monthGrowthRate = (lastMonthRecord == null || lastMonthRecord == 0)
                ? 1.0
                : (allRecord - lastMonthRecord) * 1.0 / lastMonthRecord;

        // 统计病例相关数据
        Integer caseNum = diagnosisRecordMapper.countCaseNum(id);
        Integer lastMonthCaseNum = diagnosisRecordMapper.countLastMonthCaseNum(id);

        double caseGrowthRate = (lastMonthCaseNum == null || lastMonthCaseNum == 0)
                ? 1.0
                : (caseNum - lastMonthCaseNum) * 1.0 / lastMonthCaseNum;

        // 统计患者数据
        Integer todayPatient = diagnosisRecordMapper.countTodayPatient(id);
        Integer yesterdayPatient = diagnosisRecordMapper.countYesterdayPatient(id);

        double patientGrowthRate = (yesterdayPatient == null || yesterdayPatient == 0)
                ? 1.0
                : (todayPatient - yesterdayPatient) * 1.0 / yesterdayPatient;

        // 使用 Builder 模式构建 `DashboardVO`
        DashboardVO dashboardVO = DashboardVO.builder()
                .todayRecord(todayRecord)
                .dayGrowthRate(dayGrowthRate)
                .allRecord(allRecord)
                .monthGrowthRate(monthGrowthRate)
                .caseNum(caseNum)
                .caseGrowthRate(caseGrowthRate)
                .todayPatient(todayPatient)
                .patientGrowthRate(patientGrowthRate)
                .build();

        return dashboardVO;

    }
}
